import { ref } from 'vue'
import { astro } from 'iztro'

export function useZiwei() {
  const loading = ref(false)

  async function generateZiwei({ date, timeIndex = 0, gender = 'male', dateType = 'solar', isLeapMonth = false }) {
    loading.value = true
    try {
      // optional config
      try { astro.config && astro.config({}) } catch (e) { /* ignore */ }

      let astrolabe
      if (dateType === 'solar') {
        astrolabe = astro.bySolar(date, parseInt(timeIndex), gender, true, 'zh-CN')
      } else {
        astrolabe = astro.byLunar(date, parseInt(timeIndex), gender === 'male' ? '男' : '女', isLeapMonth, true, 'zh-CN')
      }

      const palaces = (astrolabe.palaces || []).map(p => {
        const palaceApi = typeof astrolabe.palace === 'function' ? astrolabe.palace(p.name) : null
        return {
          ...p,
          horoscopeMutagens: {
            禄: palaceApi && palaceApi.hasMutagen ? palaceApi.hasMutagen('禄') : false,
            权: palaceApi && palaceApi.hasMutagen ? palaceApi.hasMutagen('权') : false,
            科: palaceApi && palaceApi.hasMutagen ? palaceApi.hasMutagen('科') : false,
            忌: palaceApi && palaceApi.hasMutagen ? palaceApi.hasMutagen('忌') : false,
          }
        }
      })

      const fiveElementsClass = astrolabe.fiveElementsClass || astrolabe.fiveElements || ''
      const destiny = palaces.find(p => p.name === '命宫') || palaces[0] || null
      const majorStar = destiny && destiny.majorStars && destiny.majorStars.length ? destiny.majorStars.map(s => s.name).join(',') : '无主星'

      const result = {
        palaces,
        fiveElementsClass,
        majorStar,
        body: astrolabe.body || (gender === 'male' ? '太阳' : '太阴'),
        soul: astrolabe.soul || '',
        chineseDate: astrolabe.chineseDate || (dateType === 'solar' ? new Date(date).toLocaleDateString() : `农历 ${date}`),
        solarDate: astrolabe.solarDate || new Date(date).toLocaleString(),
        lunarDate: astrolabe.lunarDate || null,
        destinyPalaceIndex: palaces.findIndex(p => p.name === '命宫')
      }

      loading.value = false
      return result
    } catch (err) {
      loading.value = false
      // 上抛异常，由页面层处理（不再使用模拟）
      throw err
    }
  }

  return { loading, generateZiwei }
}
